package cn.dlc.com.order.config;

import cn.dlc.com.order.entity.Product;
import com.netflix.hystrix.*;
import org.springframework.web.client.RestTemplate;

public class OrderCommand extends HystrixCommand<Product> {

    private RestTemplate restTemplate;

    private String id;

    public OrderCommand(RestTemplate restTemplate, String id) {
        super(setter());
        this.id = id;
        this.restTemplate = restTemplate;
    }

    private static Setter setter(){
        // 创建一个分组服务
        HystrixCommandGroupKey commandGroupKey = HystrixCommandGroupKey.Factory.asKey("order-group");

        // 服务标志
        HystrixCommandKey commandKey = HystrixCommandKey.Factory.asKey("product");

        // 线程池名称
        HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("order-server-divide");

        // hystrix的线程池配置
        // 1、withCoreSize：线程池大小；
        // 2、withKeepAliveTimeMinutes：线程存活时间15s
        // 3、withQueueSizeRejectionThreshold：队列等待的阈值，超过这个值执行拒绝
        HystrixThreadPoolProperties.Setter poolProperties = HystrixThreadPoolProperties
                .Setter().withCoreSize(50)
                .withKeepAliveTimeMinutes(15)
                .withQueueSizeRejectionThreshold(100);

        // 开启超时
        HystrixCommandProperties.Setter commandProperties = HystrixCommandProperties.Setter()
                .withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.THREAD)
                .withExecutionTimeoutInMilliseconds(5000);
//                .withExecutionTimeoutEnabled(true);

        return Setter.withGroupKey(commandGroupKey)
                .andCommandKey(commandKey)
                .andThreadPoolKey(threadPoolKey)
                .andThreadPoolPropertiesDefaults(poolProperties)
                .andCommandPropertiesDefaults(commandProperties);
    }


    @Override
    protected Product run() throws Exception {
        System.out.println("findById " + Thread.currentThread().getName());
        return restTemplate.getForObject("http://product-server/product/" + id, Product.class);
    }

    @Override
    protected Product getFallback() {
        Product product = new Product();
        product.setDesc("降级了！！！");
        return product;
    }
}
